package com.yry.security;

import java.security.Key;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

import org.apache.commons.codec.binary.Base64;
import org.junit.Test;

/**
 * 对称加密算法：PBE,Password Based Encryption,基于口令加密
 * 结合了消息摘要算法和对称加密算法的优点
 * 对已有算法的包装
 * 盐
 * PBEWithMD5AndDES
 * @author Administrator
 *
 */
public class ImoocPbe {
	private static String srcStr = "imooc security pbe";
	
	@Test
	public void jdkPbe(){
		try {
			//初始化盐
			SecureRandom random = new SecureRandom();
			byte[] salt = random.generateSeed(8);
			
			//口令与密钥
			String password = "imooc";
			PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
			SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEWITHMD5andDES");
			Key key = factory.generateSecret(pbeKeySpec);
			
			//加密
			PBEParameterSpec pbeParameterSpec = new PBEParameterSpec(salt,100);
			Cipher cipher = Cipher.getInstance("PBEWITHMD5andDES");
			cipher.init(Cipher.ENCRYPT_MODE, key,pbeParameterSpec);
			byte[] result = cipher.doFinal(srcStr.getBytes());
			String resultStr = Base64.encodeBase64String(result);
			System.out.println("JDK PBE encrypt加密:"+resultStr);
			
			//解密
			cipher.init(Cipher.DECRYPT_MODE, key,pbeParameterSpec);
			result = cipher.doFinal(result);
			resultStr =new String(result);
			System.out.println("JDK PBE decrypt解密:"+resultStr);
			
		} catch (Exception e) {
			e.printStackTrace();
		} 
		
		
	}

}
